package com.zhuiyi.yiqingbackend.service.impl;

import com.zhuiyi.yiqingbackend.common.ErrorCode;
import com.zhuiyi.yiqingbackend.domain.Base;
import com.zhuiyi.yiqingbackend.domain.Dead;
import com.zhuiyi.yiqingbackend.domain.Patient;
import com.zhuiyi.yiqingbackend.domain.request.AddDeadRequest;
import com.zhuiyi.yiqingbackend.exception.BusinessException;
import com.zhuiyi.yiqingbackend.mapper.BaseMapper;
import com.zhuiyi.yiqingbackend.mapper.DeadMapper;
import com.zhuiyi.yiqingbackend.service.BaseService;
import com.zhuiyi.yiqingbackend.service.DeadService;
import com.zhuiyi.yiqingbackend.service.PatientService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class DeadServiceImpl implements DeadService {
    @Resource
    private DeadMapper deadMapper;
    @Resource
    private BaseService baseService;
    @Resource
    private PatientService patientService;
    @Resource
    private BaseMapper baseMapper;

    @Override
    public List<Dead> getDeads() {
        List<Dead> deads = deadMapper.getDeads();
        if (deads == null) {
            throw new BusinessException(ErrorCode.GET_FAIL);
        }
        for (int i = 0; i < deads.size(); i++) {
            int baseid = deads.get(i).getBaseid();
            Base base = baseService.getBaseById(baseid);
            deads.get(i).setBase(base);
            Patient patient = patientService.getPatientByBaseID(baseid);
            deads.get(i).setPatient(patient);
        }
        return deads;
    }

    @Override
    public Dead getDeadById(int id) {
        Dead dead = deadMapper.getDeadById(id);
        if (dead == null) {
            throw new BusinessException(ErrorCode.GET_FAIL);
        }
        Base base = baseService.getBaseById(dead.getBaseid());
        dead.setBase(base);
        return dead;
    }

    @Override
    public boolean addDead(AddDeadRequest request) {
        int baseid = baseService.getBaseByPhone(request.getPhone()).getId();
        Dead dead = new Dead(request, baseid);
        boolean result = deadMapper.addDead(dead);
        if (!result) {
            throw new BusinessException(ErrorCode.INSERT_FAIL);
        }
        return result;
    }

    @Override
    public boolean deleteDead(int id) {
        Dead dead = deadMapper.getDeadById(id);
        if (dead == null) {
            throw new BusinessException(ErrorCode.GET_FAIL);
        }
        boolean result = deadMapper.deleteDead(id);
        if (!result) {
            throw new BusinessException(ErrorCode.DELETE_FAIL);
        }
        return result;
    }

    @Override
    public boolean addDead2(int id) {
        Dead dead = new Dead();
        dead.setBaseid(id);
        boolean result = deadMapper.addDead(dead);
        return result;
    }
}
